<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Java web," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="说明：Hibernate配置使用。">
<meta name="keywords" content="Java web">
<meta property="og:type" content="article">
<meta property="og:title" content="Hibernate">
<meta property="og:url" content="http://bebetter.site/2017/01/12/Software/Java Web/Hibernate/index.html">
<meta property="og:site_name" content="gatewayzy">
<meta property="og:description" content="说明：Hibernate配置使用。">
<meta property="og:updated_time" content="2017-01-12T05:58:56.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Hibernate">
<meta name="twitter:description" content="说明：Hibernate配置使用。">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"right","display":"always"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://bebetter.site/2017/01/12/Software/Java Web/Hibernate/"/>

  <title> Hibernate | gatewayzy </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">gatewayzy</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">blog of gatewayzy</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Hibernate
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2017-01-12T13:58:08+08:00" content="2017-01-12">
              2017-01-12
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Softwares/" itemprop="url" rel="index">
                    <span itemprop="name">Softwares</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><strong>说明：</strong>Hibernate配置使用。<br><a id="more"></a></p>
<hr>
<p>参考文章：</p>
<h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><hr>
<p>Hibernate属于一种ORM框架（Object Relational Mapping，对象关系映射），ORM主要进行面向对象与关系型数据库之间的映射，属于数据持久层技术。</p>
<h3 id="Hibernate与mybatis相比的优劣"><a href="#Hibernate与mybatis相比的优劣" class="headerlink" title="Hibernate与mybatis相比的优劣"></a>Hibernate与mybatis相比的优劣</h3><ul>
<li>Hibernate具有良好的数据映射机制，不用写sql语句，数据库移植性好，缓存机制完善。但是表的关联操作配置麻烦，对sql的优化不方便。</li>
<li>Mybatis要手动编写sql，可以细粒度的优化sql，对数据库操作方便灵活。但是数据库移植需要重写sql，需要维护sql与结果的映射，自带的缓存自己不佳。</li>
</ul>
<h3 id="Hibernate与jdbc"><a href="#Hibernate与jdbc" class="headerlink" title="Hibernate与jdbc"></a>Hibernate与jdbc</h3><ul>
<li>jdbc是用什么查什么，减少带宽。</li>
<li>Hibernate建议将对象的字段全部取出，方便封装成一个类，并且可以支持表格关联。如果使用HQL选取部分属性，不仅要再进行封装进行使用，而且不利于表格关联操作。</li>
</ul>
<hr>
<h2 id="Hibernate配置及demo"><a href="#Hibernate配置及demo" class="headerlink" title="Hibernate配置及demo"></a>Hibernate配置及demo</h2><p>Hibernate开发方式一般分为从3种：</p>
<ol>
<li>是先写Pojo，再写mapping，再自动生成db（这是官方推荐，部分人用这种方式）。</li>
<li>是建立db，用工具生成mapping和pojo（使用较多）。</li>
<li>是先写mapping，再写Pojo和db，比较少见。<br>我们采用第二种方式，先建好数据库和表，代码来自javaTools。</li>
</ol>
<h3 id="Domain对象-javabean-pojo-data对象"><a href="#Domain对象-javabean-pojo-data对象" class="headerlink" title="Domain对象/javabean/pojo/data对象"></a>Domain对象/javabean/pojo/data对象</h3><p>一般一张表对应一个pojo对象（plain ordinary java object，简单Java对象）。<br>一个pojo序列化，含主键、私有成员、无参构造器、get与set方法。<br>一般Pojo类名用首字母大写的表名，字段名也相似。<br>Hibernate推荐每一张表都有一个独立的主键，并且这个主键和业务逻辑无关，这样能够保证主键独立性。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div></pre></td><td class="code"><pre><div class="line">package hibernate.domain;</div><div class="line">import java.io.Serializable;</div><div class="line">/**</div><div class="line"> * 序列化实现对象的唯一标识，便于网络传输等</div><div class="line"> * </div><div class="line"> * @author dell</div><div class="line"> *</div><div class="line"> */</div><div class="line">public class Customer implements Serializable &#123;</div><div class="line">	private static final long serialVersionUID = 1L;</div><div class="line">	</div><div class="line">	private int id;</div><div class="line">	private String userName;</div><div class="line">	private String passwd;</div><div class="line">	public int getId() &#123;</div><div class="line">		return id;</div><div class="line">	&#125;</div><div class="line">	public void setId(int id) &#123;</div><div class="line">		this.id = id;</div><div class="line">	&#125;</div><div class="line">	public String getUserName() &#123;</div><div class="line">		return userName;</div><div class="line">	&#125;</div><div class="line">	public void setUserName(String userName) &#123;</div><div class="line">		this.userName = userName;</div><div class="line">	&#125;</div><div class="line">	public String getPasswd() &#123;</div><div class="line">		return passwd;</div><div class="line">	&#125;</div><div class="line">	public void setPasswd(String passwd) &#123;</div><div class="line">		this.passwd = passwd;</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="Mapping文件"><a href="#Mapping文件" class="headerlink" title="Mapping文件"></a>Mapping文件</h3><p>映射文件描述Pojo对象与数据表字段的映射关系。一般mapping文件用Pojo名加上后缀名.hbm.xml。<strong>注意在xml中开头第一行不能是空行或其他，必须是&lt;?xml&gt;</strong>.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</div><div class="line">&lt;!-- 该文件用于ORM映射 --&gt;</div><div class="line">&lt;!-- mapping文件需要的dtd --&gt;</div><div class="line">&lt;!DOCTYPE hibernate-mapping PUBLIC</div><div class="line">	&quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot;</div><div class="line">	&quot;http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd&quot;&gt;</div><div class="line">	</div><div class="line">&lt;hibernate-mapping package=&quot;hibernate.domain&quot;&gt;</div><div class="line">	&lt;!-- 配置domain对象与表的对应关系 --&gt;</div><div class="line">	&lt;class name=&quot;Customer&quot; table=&quot;customer&quot;&gt;</div><div class="line">		&lt;!-- 配置主键 --&gt;</div><div class="line">		&lt;id name=&quot;id&quot; column=&quot;id&quot; type=&quot;java.lang.Integer&quot;&gt;</div><div class="line">			&lt;!-- 主键生成策略hilo，native，increment，sequence... --&gt;</div><div class="line">			&lt;generator class=&quot;increment&quot;&gt;</div><div class="line">				&lt;!-- &lt;param name=&quot;auto_inc&quot;&gt;emp_inc&lt;/param&gt; --&gt;</div><div class="line">			&lt;/generator&gt;</div><div class="line">		&lt;/id&gt;</div><div class="line">		&lt;!-- 配置其他属性 --&gt;</div><div class="line">		&lt;property name=&quot;userName&quot; type=&quot;java.lang.String&quot;&gt;</div><div class="line">			&lt;column name=&quot;username&quot; not-null=&quot;false&quot;&gt;&lt;/column&gt;</div><div class="line">		&lt;/property&gt;</div><div class="line">		&lt;!-- 配置其他属性 --&gt;</div><div class="line">		&lt;property name=&quot;passwd&quot; type=&quot;java.lang.String&quot;&gt;</div><div class="line">			&lt;column name=&quot;password&quot; not-null=&quot;false&quot;&gt;&lt;/column&gt;</div><div class="line">		&lt;/property&gt;</div><div class="line">	&lt;/class&gt;</div><div class="line">&lt;/hibernate-mapping&gt;</div></pre></td></tr></table></figure>
<h3 id="hibernate-cfg-xml"><a href="#hibernate-cfg-xml" class="headerlink" title="hibernate.cfg.xml"></a>hibernate.cfg.xml</h3><p>hibernate.cfg.xml是hibernate的配置文件，包括数据库配置，mapping文件路径等，该名称是默认的配置文件名。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div></pre></td><td class="code"><pre><div class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</div><div class="line">&lt;!-- 配置文件需要的dtd --&gt;</div><div class="line">&lt;!DOCTYPE hibernate-configuration PUBLIC</div><div class="line">	&quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;</div><div class="line">	&quot;http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd&quot;&gt;</div><div class="line"></div><div class="line">&lt;hibernate-configuration&gt;</div><div class="line">	&lt;!-- 配置与数据库的session会话 --&gt;</div><div class="line">	&lt;session-factory&gt;</div><div class="line">		&lt;!-- 配置数据库参数 --&gt;</div><div class="line">		&lt;property name=&quot;connection.driver_class&quot;&gt;com.mysql.jdbc.Driver&lt;/property&gt;</div><div class="line">		&lt;property name=&quot;connection.url&quot;&gt;jdbc:mysql://127.0.0.1:3306/javatools&lt;/property&gt;</div><div class="line">		&lt;property name=&quot;connection.username&quot;&gt;root&lt;/property&gt;</div><div class="line">		&lt;property name=&quot;connection.password&quot;&gt;1234&lt;/property&gt;</div><div class="line">		</div><div class="line">		&lt;!-- 配置数据库方言，hibernate自动会根据翻译成sql方言 --&gt;</div><div class="line">		&lt;property name=&quot;dialect&quot;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;</div><div class="line">		&lt;!-- 配置可以使用getCurrentSession，线程绑定 --&gt;</div><div class="line">		&lt;property name=&quot;current_session_context_class&quot;&gt;thread&lt;/property&gt;</div><div class="line">		&lt;!-- 显示运行的sql --&gt;</div><div class="line">		&lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;</div><div class="line">		&lt;!-- 根据映射文件自动创建数据表,create表示每次创建，update为更新，若没有创建 --&gt;</div><div class="line">		&lt;property name=&quot;hbm2ddl.auto&quot;&gt;update&lt;/property&gt;</div><div class="line">		&lt;!-- 配置mapping文件 --&gt;</div><div class="line">		&lt;mapping resource=&quot;hibernate/Customer.hbm.xml&quot; /&gt;</div><div class="line">		</div><div class="line">	&lt;/session-factory&gt;</div><div class="line">&lt;/hibernate-configuration&gt;</div></pre></td></tr></table></figure>
<h3 id="业务与控制"><a href="#业务与控制" class="headerlink" title="业务与控制"></a>业务与控制</h3><p>一般一个SessionFactory对应一个数据库，利用该工厂建立多个连接（session），所以该工厂可以抽取出来（只使用一个数据库时）。</p>
<h4 id="SessionFactory工具类"><a href="#SessionFactory工具类" class="headerlink" title="SessionFactory工具类"></a>SessionFactory工具类</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div></pre></td><td class="code"><pre><div class="line">package hibernate.util;</div><div class="line"></div><div class="line">import org.hibernate.SessionFactory;</div><div class="line">import org.hibernate.cfg.Configuration;</div><div class="line"></div><div class="line">/**</div><div class="line"> * 写一个sessionFactory的工具类，且不允许继承，因为一个数据库最好只用一个sessionFactory</div><div class="line"> * </div><div class="line"> * @author dell</div><div class="line"> *</div><div class="line"> */</div><div class="line">final public class MySessionFactory &#123;</div><div class="line">	private static SessionFactory sessionFactory = null;</div><div class="line"></div><div class="line">	private MySessionFactory() &#123;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	// 静态化的代码块，只会被执行一次</div><div class="line">	static &#123;</div><div class="line">		// 创建Configuration来读取hibernate.cfg.xml，默认该文件名可以不用写</div><div class="line">		Configuration configuration = new Configuration().configure(&quot;hibernate.cfg.xml&quot;);</div><div class="line">		// 创建数据库的sessionFactory，这是一个重量级的对象，一个sessionFactory对应一个数据库</div><div class="line">		sessionFactory = configuration.buildSessionFactory();</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	public static SessionFactory getSessionFactory() &#123;</div><div class="line">		return sessionFactory;</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h4 id="测试主函数"><a href="#测试主函数" class="headerlink" title="测试主函数"></a>测试主函数</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div></pre></td><td class="code"><pre><div class="line">package hibernate.view;</div><div class="line">import java.util.Date;</div><div class="line">import org.hibernate.Session;</div><div class="line">import org.hibernate.SessionFactory;</div><div class="line">import org.hibernate.Transaction;</div><div class="line">import org.hibernate.cfg.Configuration;</div><div class="line">import hibernate.domain.Customer;</div><div class="line">import hibernate.util.MySessionFactory;</div><div class="line"></div><div class="line">/**</div><div class="line"> * 使用hibernate实现数据库crud</div><div class="line"> * </div><div class="line"> * @param args</div><div class="line"> */</div><div class="line">public class MyHibernate &#123;</div><div class="line">	public static void main(String[] args) &#123;</div><div class="line">		addCustomer();</div><div class="line">		addCustomer();</div><div class="line">		addCustomer();</div><div class="line">		retrievalCustomer();</div><div class="line">		updateCustomer();</div><div class="line">		deleteCustomer();</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	/**</div><div class="line">	 * 插入一条数据</div><div class="line">	 */</div><div class="line">	public static void addCustomer() &#123;</div><div class="line">		System.err.println(&quot;准备插入一个数据&quot;);</div><div class="line">		// 创建Configuration来读取hibernate.cfg.xml，默认该文件名可以不用写</div><div class="line">		Configuration configuration = new Configuration().configure(&quot;hibernate.cfg.xml&quot;);</div><div class="line">		// 创建数据库的sessionFactory，这是一个重量级的对象，一个sessionFactory对应一个数据库</div><div class="line">		SessionFactory sessionFactory = configuration.buildSessionFactory();</div><div class="line">		// 申请数据库session（connection）使用后必须记得关闭</div><div class="line">		Session session = sessionFactory.openSession();</div><div class="line">		// hibernate要求增改删操作必须使用事务，否则不会执行</div><div class="line">		Transaction transaction = session.beginTransaction();</div><div class="line">		// 添加一个customer</div><div class="line">		Customer customer = new Customer();</div><div class="line">		customer.setUserName(&quot;zhangsan&quot;);</div><div class="line">		customer.setPasswd(new Date().toString());</div><div class="line">		session.save(customer);</div><div class="line">		transaction.commit();</div><div class="line">		session.close();</div><div class="line">		System.err.println(&quot;插入数据完成&quot;);</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	/**</div><div class="line">	 * 查询一条数据</div><div class="line">	 */</div><div class="line">	private static void retrievalCustomer() &#123;</div><div class="line">		System.err.println(&quot;准备查询数据记录&quot;);</div><div class="line">		// 通过工具获取session</div><div class="line">		Session session = MySessionFactory.getSessionFactory().openSession();</div><div class="line">		// 获取主键=2的对象，通过类名反射获取mapping</div><div class="line">		Customer customer = session.load(Customer.class, 2);</div><div class="line">		System.err.println(&quot;查询到主键为2的customer姓名为：&quot; + customer.getUserName());</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	/**</div><div class="line">	 * 更新一条数据</div><div class="line">	 */</div><div class="line">	private static void updateCustomer() &#123;</div><div class="line">		System.err.println(&quot;准备修改数据记录&quot;);</div><div class="line">		// 通过工具获取session</div><div class="line">		Session session = MySessionFactory.getSessionFactory().openSession();</div><div class="line">		Transaction transaction = session.beginTransaction();</div><div class="line">		// 获取主键=3的对象，通过类名反射获取mapping</div><div class="line">		Customer customer = session.load(Customer.class, 3);</div><div class="line">		// set会产生数据游离状态，hibernate会检测到修改，所以commit会发生改变</div><div class="line">		customer.setUserName(customer.getUserName() + &quot;1&quot;);</div><div class="line">		customer.setPasswd(new Date().toString());</div><div class="line">		transaction.commit();</div><div class="line">		session.close();</div><div class="line">		System.err.println(&quot;修改主键3的姓名为：&quot; + customer.getUserName() + &quot;1&quot;);</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	/**</div><div class="line">	 * 删除一条数据</div><div class="line">	 */</div><div class="line">	private static void deleteCustomer() &#123;</div><div class="line">		System.err.println(&quot;准备删除记录&quot;);</div><div class="line">		// 通过工具获取session</div><div class="line">		Session session = MySessionFactory.getSessionFactory().openSession();</div><div class="line">		Transaction transaction = session.beginTransaction();</div><div class="line">		try &#123;</div><div class="line">			// 获取主键=1的对象，通过类名反射获取mapping</div><div class="line">			Customer customer = session.load(Customer.class, 1);</div><div class="line">			session.delete(customer);</div><div class="line">			transaction.commit();</div><div class="line">		&#125; catch (Exception e) &#123;</div><div class="line">			if (transaction != null) &#123;</div><div class="line">				transaction.rollback();</div><div class="line">			&#125;</div><div class="line">			e.printStackTrace();</div><div class="line">		&#125; finally &#123;</div><div class="line">			session.close();</div><div class="line">		&#125;</div><div class="line">		System.err.println(&quot;删除主键1的记录成功&quot;);</div><div class="line">	&#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="Hibernate核心类、接口与配置"><a href="#Hibernate核心类、接口与配置" class="headerlink" title="Hibernate核心类、接口与配置"></a>Hibernate核心类、接口与配置</h2><h3 id="Configuration类"><a href="#Configuration类" class="headerlink" title="Configuration类"></a>Configuration类</h3><p>配置管理的类。</p>
<h3 id="Hibernate-cfg-xml"><a href="#Hibernate-cfg-xml" class="headerlink" title="Hibernate.cfg.xml"></a>Hibernate.cfg.xml</h3><p>配置数据库管理、mapping文件管理。</p>
<h3 id="Pojo-hbm-xml"><a href="#Pojo-hbm-xml" class="headerlink" title="Pojo.hbm.xml"></a>Pojo.hbm.xml</h3><p>配置Pojo与数据库之间的mapping。</p>
<h3 id="SessionFactory接口"><a href="#SessionFactory接口" class="headerlink" title="SessionFactory接口"></a>SessionFactory接口</h3><ul>
<li>SessionFactory是session工厂，获取数据库连接。</li>
<li>SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();</li>
</ul>
<h3 id="Session类操作数据库"><a href="#Session类操作数据库" class="headerlink" title="Session类操作数据库"></a>Session类操作数据库</h3><h4 id="getSession与openSession"><a href="#getSession与openSession" class="headerlink" title="getSession与openSession"></a>getSession与openSession</h4><ul>
<li>SessionFactory可以进行sql缓存，被称为session级缓存（属于一级缓存）。</li>
<li>一次请求不返回之前都可以看成一个线程。</li>
<li>SessionFactory.openSession()每次获取新的session。如果在不同的service中用不同的session就用openSession，但是注意必须手动close。</li>
<li>SessionFactory.getCurrentSession()获取当前线程绑定的session，可以进行事务控制，本方法可以自动关闭session，但是查询也要事务提交，并且要配置cfg.xml，thread为本地事务（jdbc事务，针对一个数据库），jta为全局事务（跨数据库）。</li>
<li>可以通过threadLocal将openSession与线程绑定实现getCurrentSession的功能。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div></pre></td><td class="code"><pre><div class="line">package hibernate.util;</div><div class="line"></div><div class="line">import org.hibernate.Session;</div><div class="line">import org.hibernate.SessionFactory;</div><div class="line">import org.hibernate.cfg.Configuration;</div><div class="line"></div><div class="line">/**</div><div class="line"> * 获取session的两种方法</div><div class="line"> * </div><div class="line"> * @author dell</div><div class="line"> *</div><div class="line"> */</div><div class="line">public class SessionUtil &#123;</div><div class="line">	private static SessionFactory sessionFactory = null;</div><div class="line">	private static ThreadLocal&lt;Session&gt; threadLocal = new ThreadLocal&lt;&gt;();</div><div class="line"></div><div class="line">	private SessionUtil() &#123;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	static &#123;</div><div class="line">		sessionFactory = new Configuration().configure().buildSessionFactory();</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	// 使用原生的openSession，获取全新的session</div><div class="line">	public static Session openSession() &#123;</div><div class="line">		return sessionFactory.openSession();</div><div class="line">	&#125;</div><div class="line"></div><div class="line">	// 通过threadLocal方法实现getCurrentSession的功能</div><div class="line">	public static Session getCurrentSession() &#123;</div><div class="line">		Session session = threadLocal.get();</div><div class="line">		// 判断是否得到</div><div class="line">		if (session == null) &#123;</div><div class="line">			session = sessionFactory.openSession();</div><div class="line">			// 将新建的session和线程进行绑定，之后获得的都是该session</div><div class="line">			threadLocal.set(session);</div><div class="line">		&#125;</div><div class="line">		return session;</div><div class="line">	&#125;</div><div class="line"></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<hr>
<p>下面介绍session几个重要的方法。</p>
<h4 id="保存session-save"><a href="#保存session-save" class="headerlink" title="保存session.save"></a>保存session.save</h4><p>Session.save(obj);</p>
<h4 id="删除session-delete"><a href="#删除session-delete" class="headerlink" title="删除session.delete"></a>删除session.delete</h4><p>Session.delete(obj);</p>
<h4 id="查询get、load、query、criteria"><a href="#查询get、load、query、criteria" class="headerlink" title="查询get、load、query、criteria"></a>查询get、load、query、criteria</h4><ul>
<li><p>get与load</p>
<ul>
<li>Session.get()与session.load().</li>
<li>Get直接返回实体类，查不到返回null。Load会返回一个实体代理对象，如果数据不存在会抛出异常，类似于中间件到数据的查找映射。</li>
<li>Load先到session缓存（一级缓存）与二级缓存中去查，没有也会返回代理对象（不马上到DB中找），等到使用代理对象操作时才到DB查找，这就是“load在默认情况下支持延迟加载（lazy）”，会导致DB中数据不存在的时候会抛出异常。比如连续多次load同一数据最多执行一次sql。</li>
<li>Get先到session缓存与二级缓存中去查，如果没有就马上去DB中查。</li>
<li>总之，如果确定DB中存在就用load，不确定就用get，这样会提高效率。取消load的懒加载可以配置mapping文件：<class name="Customer" lazy="false" table="customer">。</class></li>
</ul>
</li>
<li><p>query</p>
<ul>
<li>获取query引用，这里用的还是Pojo对象不是表名，条件中的可以是表的字段名也可以是Pojo成员名，推荐是Pojo成员名。</li>
<li>如果确定一个查询结果最多一个结果，推荐使用uniqueResult()，取代list()，可以在查找到一个结果后及时返回结果。</li>
</ul>
</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">Query query = session.createQuery(&quot;from Customer where userName=&apos;zhangsan&apos;&quot;);</div><div class="line">public static void main(String[] aStrings) &#123;</div><div class="line">		Session session = SessionUtil.openSession();</div><div class="line">		Transaction transaction = session.beginTransaction();</div><div class="line"></div><div class="line">		// 获取query引用，这里用的还是Pojo对象不是表名，条件中的可以是表的字段名也可以是Pojo成员名，推荐是Pojo成员名</div><div class="line">		Query query = session.createQuery(&quot;from Customer where userName=&apos;zhangsan&apos;&quot;);</div><div class="line">		// Query query = session.createQuery(&quot;from Customer where id=1);</div><div class="line">		List&lt;Customer&gt; list = query.list();</div><div class="line">		for (Customer customer : list) &#123;</div><div class="line">			System.out.println(&quot;查询到的数据信息为：&quot;);</div><div class="line">			System.out.println(customer.getId() + &quot; &quot; + customer.getPasswd());</div><div class="line">		&#125;</div><div class="line">	session.close();</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<ul>
<li><p>criteria<br>criteria不太常用，主要是面向Pojo成员添加条件限制。<br>private static void criteria() {</p>
<pre><code>Session session = SessionUtil.openSession();
Transaction transaction = session.beginTransaction();

Criteria criteria = session.createCriteria(Customer.class).add(Restrictions.like(&quot;userName&quot;, &quot;zhang%&quot;))
        .setMaxResults(2).addOrder(Order.desc(&quot;id&quot;));
List&lt;Customer&gt; list = criteria.list();
for (Customer customer : list) {
    System.out.println(&quot;查询到的数据信息为：&quot;);
    System.out.println(customer.getId() + &quot; &quot; + customer.getUserName() + &quot; &quot; + customer.getPasswd());
}
session.close();
</code></pre><p>  }</p>
</li>
<li><p>修改<br>Update.</p>
</li>
</ul>
<h3 id="事务"><a href="#事务" class="headerlink" title="事务"></a>事务</h3><p>Hibernate的操作除了查询之外，其他都必须使用事务进行操作，基本方式如下。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line">Session session = MySessionFactory.getSessionFactory().openSession();</div><div class="line">	Transaction transaction = null;</div><div class="line">	try &#123;</div><div class="line">		transaction = session.beginTransaction();</div><div class="line">		// do something</div><div class="line">		transaction.commit();</div><div class="line">	&#125; catch (Exception e) &#123;</div><div class="line">		if (transaction != null) &#123;</div><div class="line">			transaction.rollback();</div><div class="line">		&#125;</div><div class="line">	&#125; finally &#123;</div><div class="line">		session.close();</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<h3 id="Hibernate表格关联"><a href="#Hibernate表格关联" class="headerlink" title="Hibernate表格关联"></a>Hibernate表格关联</h3><p>Hibernate的表格关联，在pojo中引用的外键变成引用对象，关系包括one-to-many，many-to-one，one-to-one。相应的属性配置就不能用<property>。<br>多个雇员属于一个部门的多对一情况下, 比如Customer拥有外键IdCard：<br>Customer Pojo中的外键是集合：private Set <idcard> IdCard;<br>可以获取一个customer引用的所有外键：Set <idcard> list = customer.getIdCard();<br>可以直接将student，course，grade三张表进行关联查询，只需在Studcourse的Pojo中配置对相应的字段。<br><code>List&lt;Object[]&gt; list = session.createQuery(“Select student.sname,cource.cname,grade from Studcourse”)</code></idcard></idcard></property></p>
<p>Hibernate存在懒加载现象，即默认情况下，返回的只是对象的普通属性，当用户使用对象属性（外键属性）的时候，才会向数据库再发出一次请求，这就是lazy加载。解决方法可以有：</p>
<ol>
<li>显示初始化hibernate.initized（代理对象）</li>
<li>修改mapping文件lazy=false</li>
<li>web项目可以过滤器，openSessionView</li>
</ol>
<hr>
<h2 id="HQL-Hibernate-Query-Language"><a href="#HQL-Hibernate-Query-Language" class="headerlink" title="HQL-Hibernate Query Language"></a>HQL-Hibernate Query Language</h2><p>HQL是hibernate官方推荐的操作语言，可以弥补单薄的save、delete、query等操作方法。<br>HQL与SQL不同，HQL区分大小写（仅区分java类和属性），HQL查找的是对象不是表，且支持多态，HQL主要通过query进行操作。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">public static void main(String[] args) &#123;</div><div class="line">	Session session = SessionUtil.getCurrentSession();</div><div class="line">	Transaction transaction = session.beginTransaction();</div><div class="line">	// 检索所有的customer，是从对象</div><div class="line">	List&lt;Customer&gt; list = session.createQuery(&quot;from Customer&quot;).list();</div><div class="line">	for (Customer customer : list) &#123;</div><div class="line">		System.out.println(customer.getUserName() + &quot; &quot; + customer.getId());</div><div class="line">	&#125;</div><div class="line">	transaction.commit();</div><div class="line">	if (transaction != null) &#123;</div><div class="line">		transaction.rollback();</div><div class="line">	&#125;</div><div class="line">	session.close();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>HQL的query与SQL相似，但是注意查询对象是Pojo对象不是表。HQL的条件、排序等都和SQL语法类似。如where、order by、group by、函数等。<br>Hibernate推荐选取所有属性作为pojo对象。选取部分属性的话要使用Object[]存储一个对象，但如果只有一个属性，获取的时候是Object[]，输出的时候是Object.toString而不是数组了。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">Transaction transaction = session.beginTransaction();</div><div class="line">// 检索所有的customer，是从对象</div><div class="line">List&lt;Object[]&gt; list = session.createQuery(&quot;select userName,passwd from Customer where id = 2&quot;).list();</div><div class="line">for (Object[] customer : list) &#123;</div><div class="line">	System.out.println(customer[0].toString() + &quot; &quot; + customer[1].toString());</div><div class="line">&#125;</div><div class="line">System.out.println();</div><div class="line">transaction.commit();</div><div class="line">session.close();</div></pre></td></tr></table></figure>
<h3 id="HQL分页"><a href="#HQL分页" class="headerlink" title="HQL分页"></a>HQL分页</h3><ul>
<li>分页的时候可以使用setFirstResult和setMaxResults设置起止数据条数。</li>
<li>session.createQuery(“…”).setFirstResult(10).setMaxResults(20).list()</li>
<li>分页时后台首先查找所有数据总数，再查找，hibernate一共会进行3次过滤。</li>
</ul>
<h3 id="HQL参数绑定"><a href="#HQL参数绑定" class="headerlink" title="HQL参数绑定"></a>HQL参数绑定</h3><ul>
<li>参数绑定的好处：可读性好、性能提高、防止sql注入。</li>
<li>常用方法：<pre><code>Query query1 = session.createQuery(&quot;from Customer where id=:a&quot;);
query1.setString(&quot;a&quot;,&quot;2&quot;);  //string赋值
Query query2 = session.createQuery(&quot;from Customer where id=?&quot;);
query2.setString(0,&quot;2&quot;);  // index赋值
// 可以用循环setString的方法设置多个参数。
</code></pre></li>
</ul>
<h3 id="HQL语句放到xml文件中"><a href="#HQL语句放到xml文件中" class="headerlink" title="HQL语句放到xml文件中"></a>HQL语句放到xml文件中</h3><p>一些经常变化的HQL语句就可以放到Pojo的xml中，通过session.getNamedQuery()获取这个Query。一般不太常用。</p>
<hr>
<h2 id="Hibernate数据状态"><a href="#Hibernate数据状态" class="headerlink" title="Hibernate数据状态"></a>Hibernate数据状态</h2><ul>
<li>根据数据是否在数据库中存在以及是否处于session管理之下，数据对象的状态分为三种：瞬时态、持久态、脱管态（游离态）。</li>
<li>瞬时态transient：不处于session管理下，在数据库中没有对应的数据。超过作用域会被gc，一般是new出来且没与session关联的对象。</li>
<li>持久态persistent：处于session管理下，在数据库中有对应的记录。操作并commit后修改数据库。</li>
<li>脱管态detached：不处于session管理下，在数据库中有相应的记录。</li>
</ul>
<hr>
<h2 id="Hibernate缓存"><a href="#Hibernate缓存" class="headerlink" title="Hibernate缓存"></a>Hibernate缓存</h2><ul>
<li>Hibernate有一级缓存（session级缓存）与二级缓存（SessionFactory共享缓存）。</li>
<li>一级缓存就是不需要配置，使用get、save等方法的时候会自动放入缓存，但是缓存空间的大小没有保护机制，需要程序员自己使用session.clear()、evict等方法清除session缓存防止内存溢出。</li>
<li>一级缓存可以使用hashmap来模拟缓存实现的机制：将key与Object放到Map中，查数据库的时候先查看Map中是否存在，没有则查数据库并添加到map。</li>
<li>二级缓存需要配置，hibernate本身的二级缓存机制没有第三方的Hashtable、EHCache、OSCache等缓存机制做的好。Hashtable属于内存缓存，EHCache、OSCache会使用内存兼硬盘进行缓存。比如使用OSCache，需要在hibernate.cfg.xml中配置启用相应的OSCache，设置默认的OSCache.xml内容，在hibernate中可以通过sessionFactory获取其statistics统计对象信息等。</li>
</ul>
<hr>
<h2 id="IDE的hibernate开发使用"><a href="#IDE的hibernate开发使用" class="headerlink" title="IDE的hibernate开发使用"></a>IDE的hibernate开发使用</h2><ul>
<li>安装hibernate支持插件，配置相应的包名等，即可自动创建hibernate的配置文件、Pojo等代码。如新建一个maven项目，选择webapp模板，并设置默认jar修复文件默认目录，然后创建hibernate ORM框架。</li>
<li>对应的jsp创建也可以使用插件或者框架实现，如struts框架插件。一般来说经常使用创建一个web工程，插入struts框架（或者jsp+servlet框架），再插入hibernate框架，再通过引入spring框架进行全局管理。</li>
</ul>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java-web/" rel="tag">#Java web</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/01/12/Software/Automated build tools 自动化构建工具/Gradle/" rel="next" title="Gradle">
                <i class="fa fa-chevron-left"></i> Gradle
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/01/12/Software/Integrated development environment 继承开发环境 IDE/IDEA/" rel="prev" title="IDEA">
                IDEA <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    


  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/statics/images/avatar.png"
               alt="gatewayzy" />
          <p class="site-author-name" itemprop="name">gatewayzy</p>
          <p class="site-description motion-element" itemprop="description">blog website with hexo and github pages</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">70</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">38</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="https://github.com/gatewayzy" title="Github-gatewayzy" target="_blank">Github-gatewayzy</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://google.com/" title="Goolge" target="_blank">Goolge</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://wiki.jikexueyuan.com/" title="Wiki-jike" target="_blank">Wiki-jike</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Hibernate与mybatis相比的优劣"><span class="nav-number">1.1.</span> <span class="nav-text">Hibernate与mybatis相比的优劣</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Hibernate与jdbc"><span class="nav-number">1.2.</span> <span class="nav-text">Hibernate与jdbc</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Hibernate配置及demo"><span class="nav-number">2.</span> <span class="nav-text">Hibernate配置及demo</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Domain对象-javabean-pojo-data对象"><span class="nav-number">2.1.</span> <span class="nav-text">Domain对象/javabean/pojo/data对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Mapping文件"><span class="nav-number">2.2.</span> <span class="nav-text">Mapping文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#hibernate-cfg-xml"><span class="nav-number">2.3.</span> <span class="nav-text">hibernate.cfg.xml</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#业务与控制"><span class="nav-number">2.4.</span> <span class="nav-text">业务与控制</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#SessionFactory工具类"><span class="nav-number">2.4.1.</span> <span class="nav-text">SessionFactory工具类</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#测试主函数"><span class="nav-number">2.4.2.</span> <span class="nav-text">测试主函数</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Hibernate核心类、接口与配置"><span class="nav-number">3.</span> <span class="nav-text">Hibernate核心类、接口与配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Configuration类"><span class="nav-number">3.1.</span> <span class="nav-text">Configuration类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Hibernate-cfg-xml"><span class="nav-number">3.2.</span> <span class="nav-text">Hibernate.cfg.xml</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Pojo-hbm-xml"><span class="nav-number">3.3.</span> <span class="nav-text">Pojo.hbm.xml</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SessionFactory接口"><span class="nav-number">3.4.</span> <span class="nav-text">SessionFactory接口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Session类操作数据库"><span class="nav-number">3.5.</span> <span class="nav-text">Session类操作数据库</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#getSession与openSession"><span class="nav-number">3.5.1.</span> <span class="nav-text">getSession与openSession</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#保存session-save"><span class="nav-number">3.5.2.</span> <span class="nav-text">保存session.save</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#删除session-delete"><span class="nav-number">3.5.3.</span> <span class="nav-text">删除session.delete</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#查询get、load、query、criteria"><span class="nav-number">3.5.4.</span> <span class="nav-text">查询get、load、query、criteria</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#事务"><span class="nav-number">3.6.</span> <span class="nav-text">事务</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Hibernate表格关联"><span class="nav-number">3.7.</span> <span class="nav-text">Hibernate表格关联</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#HQL-Hibernate-Query-Language"><span class="nav-number">4.</span> <span class="nav-text">HQL-Hibernate Query Language</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#HQL分页"><span class="nav-number">4.1.</span> <span class="nav-text">HQL分页</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#HQL参数绑定"><span class="nav-number">4.2.</span> <span class="nav-text">HQL参数绑定</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#HQL语句放到xml文件中"><span class="nav-number">4.3.</span> <span class="nav-text">HQL语句放到xml文件中</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Hibernate数据状态"><span class="nav-number">5.</span> <span class="nav-text">Hibernate数据状态</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Hibernate缓存"><span class="nav-number">6.</span> <span class="nav-text">Hibernate缓存</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#IDE的hibernate开发使用"><span class="nav-number">7.</span> <span class="nav-text">IDE的hibernate开发使用</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">gatewayzy</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  




  
  

  
  <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
  </script>

  <script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for (i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  </script>
  <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>



  

  
<script type="text/javascript" async src="//push.zhanzhang.baidu.com/push.js">
</script>


</body>
</html>
